<?php

namespace app\admin\controller;
use think\Controller;
use think\Db;

class Login extends Controller
{
    /**
     * 用户进入登陆
     */
    public function login()
    {
        $user_name = Input('post.user_name'); //用户名
        $pass_word = Input('post.pass_word');
        if (!$user_name) {
            json_fail(data('-1', '用户名不能为空!'));
        }
        if (!$pass_word) {
            json_fail(data('-2', '密码不能为空!'));
        }
        $pass_word = encryption($pass_word);  //方法加密密码

        //初始化数据库
        $SystemManager = Db('SystemManager');
        //查询条件
        $map = array(
            'username' => $user_name,
            'password' => $pass_word
        );
        //查询数据
        $info = $SystemManager->where($map)->where('status','neq',0)->order('id desc')->find();
        if ($info) {
            //判断该用户是否被禁用 1=有效 2=禁用
            if ($info['status'] == '1') {
                //初始化数据库
                $LoginRecord = Db('LoginRecord');
                //架构准备写入登陆日志表的数据
                $data['type'] = 1;
                $data['pid'] = $info['id'];    //系统管理员id
                $data['time'] = time();         //登陆时间
                $data['ip'] = request()->ip();  //登陆ip

                //写入数据
                $LoginRecord->insert($data);
                if($info['identity'] == 4){
                    $seller = Db('seller');
                    $region_id =  $seller ->where('id',$info['role_id'])->value('region_id');
                    $seller_name =  $seller ->where('id',$info['role_id'])->value('name');
                    $region = Db('region')->where('id',$region_id)->value('name');
                }else{
                    $region ='';
                    $region_id = '';
                    $seller_name = '';
                }
                $data = array(
                    'status' => 1,
                    'msg' => '登录成功',
                    'user_id' => encode($info['id']),
                    'user_name' => $info['username'],
                    'token' => encryption(config('token')),
                    'identity'=>$info['identity'],
                    'region_name'=>$region,
                    'seller_name'=>$seller_name,
                    'region_id'=>$region_id,
                    'seller_id'=>$info['role_id'],
                );
                json_success($data);
            } else {
                json_fail(data('-3', '该用户被禁用,请联系管理员!'));
            }
        } else {
           json_fail(data('-4', '账号或密码错误!'));
        }
    }


}
